<template>
  <div>
    <el-card class="box-card">
      <div slot="header" class="clearfix">
        <span>文章列表</span>
      </div>
      <!-- 搜索区域 -->
      <div class="search-box">
        <el-form :inline="true" :model="q">
          <el-form-item label="文章分类">
            <el-select
              v-model="q.cate_id"
              placeholder="请选择分类"
              size="small"
            >
              <el-option
                :label="item.cate_name"
                :value="item.id"
                v-for="item in ArtCateList"
                :key="item.id"
              ></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="发布状态" style="margin-left: 15px">
            <el-select v-model="q.state" placeholder="请选择状态" size="small">
              <el-option label="已发布" value="已发布"></el-option>
              <el-option label="草稿" value="草稿"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" size="small" @click="getArticleList()"
              >筛选</el-button
            >
            <el-button type="info" size="small" @click="resetForm"
              >重置</el-button
            >
          </el-form-item>
        </el-form>
        <!-- 发表文章的按钮 -->
        <el-button
          type="primary"
          size="small"
          class="btn-pub"
          @click="pubDialogVisible = true"
          >发表文章</el-button
        >
      </div>

      <!-- 文章表格区域 -->
      <el-table :data="ArticleList" style="width: 100%" border>
        <el-table-column label="文章标题" prop="title">
          <template v-slot="{ row }">
            <el-link type="primary" @click="showDetail(row.id)">
              {{ row.title }}
            </el-link>
          </template>
        </el-table-column>
        <el-table-column label="文章分类" prop="cate_name"></el-table-column>
        <el-table-column label="发布时间" prop="pub_date">
          <template v-slot="{ row }">
            {{ formatData(row.pub_date) }}
          </template>
        </el-table-column>
        <el-table-column label="状态" prop="state"></el-table-column>
        <el-table-column label="操作">
          <template v-slot="{ row }">
            <el-button type="danger" size="mini" @click="deleteArticle(row.id)">
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页区域 -->
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="q.pagenum"
        :page-sizes="[2, 3, 5, 10, 20]"
        :page-size="q.pagesize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
      >
      </el-pagination>
    </el-card>
    <!-- 查看文章详情的对话框 -->
    <el-dialog title="文章预览" :visible.sync="detailVisible" width="80%">
      <h1 class="title">{{ artDetail.title }}</h1>

      <div class="info">
        <span>作者：{{ artDetail.nickname || artDetail.username }}</span>
        <span>发布时间：{{ formatData(artDetail.pub_date) }}</span>
        <span>所属分类：{{ artDetail.cate_name }}</span>
        <span>状态：{{ artDetail.state }}</span>
      </div>

      <!-- 分割线 -->
      <el-divider></el-divider>

      <img
        :src="'http://big-event-vue-api-t.itheima.net' + artDetail.cover_img"
        alt=""
      />

      <div v-html="artDetail.content"></div>
    </el-dialog>
    <!-- 发布文章的对话框start -->
    <el-dialog
      title="发表文章"
      :visible.sync="pubDialogVisible"
      fullscreen
      :before-close="handleClose"
      @closed="closeResetForm"
    >
      <!-- 发布文章的表单区域end-->
      <!-- 发布文章的对话框 -->
      <el-form
        :model="pubForm"
        :rules="pubFormRules"
        ref="pubFormRef"
        label-width="100px"
      >
        <el-form-item label="文章标题" prop="title">
          <el-input v-model="pubForm.title" placeholder="请输入标题"></el-input>
        </el-form-item>
        <el-form-item label="文章分类" prop="cate_id">
          <el-select
            v-model="pubForm.cate_id"
            placeholder="请选择分类"
            style="width: 100%"
          >
            <!-- 循环渲染分类的可选项 -->
            <el-option
              v-for="item in ArtCateList"
              :key="item.id"
              :label="item.cate_name"
              :value="item.id"
            ></el-option>
          </el-select>
        </el-form-item>
        <!-- 内容 -->
        <el-form-item lanel="文章内容" prop="content">
          <!-- 使用v-model 经行双向的数据绑定 -->
          <quill-editor v-model="pubForm.content"></quill-editor>
        </el-form-item>
        <el-form-item label="文章封面">
          <!-- 用来显示封面的图片 -->
          <img
            src="../../../assets/images/cover.jpg"
            alt=""
            class="cover-img"
            ref="imgRef"
          />
          <br />
          <!-- 文件选择框，默认被隐藏 -->
          <input
            type="file"
            style="display: none"
            accept="image/*"
            ref="iptFile"
            @change="onChangeFile"
          />
          <!-- 选择封面的按钮 -->
          <el-button type="text" @click="$refs.iptFile.click()"
            >+ 选择封面</el-button
          >
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="pubArticle('已发布')"
            >发布文章</el-button
          >
          <el-button type="info" @click="pubArticle('草稿')"
            >存为草稿</el-button
          >
        </el-form-item>
      </el-form>
      <!-- 发布文章的表单区域end -->
    </el-dialog>
    <!-- 发布文章的对话框end -->
    <!-- 文章详情页对话框 start -->
    <!-- 文章详情页对话框 start -->
    <!-- <el-dialog
  title="提示"
  :visible.sync="detailVisible"
  width="30%"
  :before-close="handleClose">
  <span>这是一段信息</span>
  <span slot="footer" class="dialog-footer">
    <el-button @click="detailVisible = false">取 消</el-button>
    <el-button type="primary" @click="detailVisible = false">确 定</el-button>
  </span>
</el-dialog> -->
    <!-- 文章详情页对话框 end -->
  </div>
</template>

<script>
import defaultImg from "@/assets/images/cover.jpg";
import dayjs from "dayjs";
//  vue-cil 集中webpack 使用import from 到入一个图片时
// 会判断图片的大小，如果小于8kb，直接转换为base64的字符串
// 如果大于8kb，会生成一个单独的文件，import后面 返回的是一个文件的路径
export default {
  name: "ArtList",
  data() {
    return {
      // 保存详情页的数据
      artDetail: {},
      // detailVisible 控制详情页对话框和显示隐藏
      detailVisible: false,
      // 存储文章总的条数
      total: 0,
      chooseImg() {
        this.$refs.iptFile.click();
      },
      // pubForm: {
      //   // 表单的数据对象
      //   title:'',
      //   cate_id:'',
      //   // 文章的内容
      //   content:''
      // },
      // 查询参数对象
      q: {
        pagenum: 1,
        pagesize: 3,
        cate_id: "",
        state: "",
      },
      //控制发布文章对话框的显示和隐藏
      pubDialogVisible: false,
      // 表单的数据对象
      pubForm: {
        title: "",
        cate_id: "",
        // 文章的内容
        content: "",
        cover_img: null,
        state: "", //值只能是'已发布' || '草稿'
      },
      // 表单的验证规则对象
      pubFormRules: {
        title: [
          { required: true, message: "请输入文章标题", trigger: "blur" },
          {
            min: 1,
            max: 30,
            message: "文章标题的长度为1-30个字符",
            trigger: "blur",
          },
        ],
        cate_id: [
          { required: true, message: "请选择文章分类", trigger: "change" },
        ],
        content: [
          { required: true, message: "请选择输入的文章内容", trigger: "blur" },
        ],
      },
      // 保存文章分类
      ArtCateList: [],
      // 保存文章列表
      ArticleList: [],
      currentPage4: 2,
    };
  },
  created() {
    // 获取文章分类列表
    this.getArtCateList();
    // 获取文章列表的数据
    this.getArticleList();
  },
  methods: {
    // 删除文章
    deleteArticle(id) {
      this.$confirm("此操作将永久别除该文章，是否继续？", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(async () => {
          //确定删除
          const { data: res } = await this.$http.delete("/my/article/info", {
            params: { id },
          });
          if (res.code !== 0) return this.$message.error(res.message);
          this.$message.success(res.message);
          
          if (this.ArticleList.length === 1 && this.q.pagenum > 1) {
            this.q.pagenum--
          }
          // 重新获取数据
          this.getArticleList();
        })
        .catch(() => {
          // 取消
        });
    },
    // 获取详情页的数据
    async showDetail(id) {
      const { data: res } = await this.$http.get("/my/article/info", {
        params: {
          id,
        },
      });
      if (res.code === 0) {
        this.artDetail = res.data;
        this.detailVisible = true;
      }
    },
    // 重置表单
    resetForm() {
      this.q = {
        pagenum: 1,
        pagesize: 2,
        cate_id: "",
        state: "",
      };
      this.getArticleList();
    },
    // 切换每一页显示多少条时触发
    handleSizeChange(val) {
      console.log(`每页${val}条`);
      this.q.pagenum = 1;
      this.q.pagesize = val;
      this.getArticleList();
    },
    // 切换当前页码时触发
    handleCurrentChange(val) {
      console.log(`当前页：${val}`);
      this.q.pagenum = val;
      this.getArticleList();
    },
    // 格式化时间的函数
    formatData(time) {
      return dayjs(time).format("YYYY-MM-DD HH:MM:SS");
    },
    // 获取文章列表的数据
    async getArticleList() {
      // 发送请求获取数据
      const { data: res } = await this.$http.get("/my/article/list", {
        params: this.q,
      });
      if (res.code === 0) {
        this.total = res.total;
        this.ArticleList = res.data;
      }
    },
    // 重置表单
    closeResetForm() {
      this.$refs.pubFormRef.resetFields();
      this.pubForm.cover_img = null;
      this.$refs.imgRef.setAttribute("src", defaultImg);
      this.pubForm.state = "";
    },
    //发布文章
    pubArticle(state) {
      // 1.绑定了事件函数
      this.pubForm.state = state;
      // 2.表单验证
      this.$refs.pubFormRef.validate(async (valid) => {
        if (!valid) return this.$message.error("文章信息不完整");
        if (this.pubForm.cover_img === null) {
          return this.$message.error("请上传封面");
        }
        // FormData 格式 ： 网络传入数据的一种格式
        const fd = new FormData();
        //高级写法
        Object.keys(this.pubForm).forEach((key) => {
          // console.log(key, 'ok')
          // console.log(this.pubForm[key],'ok')
          fd.append(key, this.pubForm[key]);
        });

        // fd.forEach(function (value,key) {
        //   console.log(key,'---------',value)
        // })
        // 3.发送请求
        const { data: res } = await this.$http.post("/my/article/add", fd);
        if (res.code !== 0) return this.$message.error(res.message);
        this.$message.success(res.message);
        // 4.关闭对话框
        this.pubDialogVisible = false;
        // 清空 input type=file的值
        this.$refs.iptFile.value = ''
      });
    },
    // 获取图片
    onChangeFile(e) {
      const fileList = e.target.files;
      if (fileList.length > 0) {
        // 选择了图片
        console.log(fileList[0]);
        this.pubForm.cover_img = fileList[0];
        // 可以将图像转化为base64的字符串 （作业）
        // URL.createObjectURL 能够将图片对象 存储到程序的内存中，返回一个地址
        const url = URL.createObjectURL(fileList[0]);
        console.log(url, ".createObjectURL");
        this.$refs.imgRef.setAttribute("src", url);
        // this.$refs.imgRef.setAttribute('alt',123)
      } else {
        // 没有选中图片
        this.pubForm.cover_img = null;
        this.$refs.imgRef.setAttribute("src", defaultImg);
      }
    },
    async getArtCateList() {
      // 发送请求获取数据
      const { data: res } = await this.$http.get("/my/cate/list");
      if (res.code === 0) {
        this.ArtCateList = res.data;
      }
    },
    handleClose(done) {
      this.$confirm("此操作将永久删除该文件，是否继续？", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then((_) => {
          //done() 可以关闭 Dialog
          done();
        })
        .catch((_) => {});
    },
  },
};
</script>

<style lang="less" scoped>
.search-box {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  .btn-pub {
    margin-top: 5px;
  }
}
/deep/ .ql-container {
  min-height: 300px;
}

.cover_img {
  width: 400px;
  height: 200px;
  object-fit: cover;
}
</style>
